package cn.kgc.search.controller;

import cn.kgc.common.entity.Article;
import cn.kgc.search.entity.ESArticle;
import cn.kgc.search.service.ArticleService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by teacher ZHANG on 2023/2/13
 */
@RestController
public class SearchController {
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @GetMapping("/articles")
    public List<ESArticle> searchArticles(String keyword, String fromDate, String endDate, Integer pageNum) {
        NativeSearchQueryBuilder searchBuilder = new NativeSearchQueryBuilder();

        //{"match": {"title": "ChatGPT"}}
        MatchQueryBuilder matchBuilder1 = QueryBuilders.matchQuery("title", keyword);
        //{"match": {"content": "飞艇"}}
        MatchQueryBuilder matchBuilder2 = QueryBuilders.matchQuery("content", keyword);

        //"should": [{"match": {"title": "ChatGPT"}},{"match": {"content": "飞艇"}}]
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery().should(matchBuilder1).should(matchBuilder2);

        // {"range": {"createDate": {"gte": "2020-05-24","lte": "2020-05-31"}}}
        RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery("createDate")
                .from(LocalDate.parse(fromDate)).to(LocalDate.parse(endDate));

        //查询加入条件、过滤、分页（从0开始）
        searchBuilder.withQuery(boolBuilder).withFilter(rangeBuilder).withPageable(PageRequest.of(pageNum - 1, 10));

        //返回的是命中的结果
        List<ESArticle> articles = new ArrayList<>();

        SearchHits<ESArticle> hits = restTemplate.search(searchBuilder.build(), ESArticle.class);
        for (SearchHit<ESArticle> hit : hits) {
            articles.add(hit.getContent());
        }

        return articles;
    }
}
